/**
 * Created by ziyu on 17/3/30px.
 */
import React from 'react'
import moment from 'moment'
import { Button, Col, DatePicker, Form, Input, message, Modal, Pagination, Popconfirm, Row, Table } from 'antd'
import Search from '../../common/components/Search'
import searchStyle from '../../common/less/search.less'
import { exportFile, fetchPost } from '../../../utils/request'
import Styles from './index.less'
import DlButton from '../../common/components/download/DlButton'

const PAGE_SIZE = 10
const { Column, ColumnGroup } = Table
const FormItem = Form.Item

class ServiceCharge extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      serviceChargeList: [],
      serviceChargeInfo: {},
      visible: false,
      currentBatchNo: '',
      params: {
        transferDateStart: moment().subtract('days', 30),
        transferDateEnd: moment().add('days', 0),
        status: '0',
        batchNo: ''
      },
      page: {
        currentPage: 1,
        pageSize: PAGE_SIZE,
        totalCount: 0
      },
      searchParams: {
        list: [
          {
            name: 'Transfer Date',
            type: 'range',
            key: ['transferDateStart', 'transferDateEnd'],
            className: 'pr20',
            placeHolder: '',
            values: [
              moment().subtract('days', 30),
              moment().add('days', 0)
            ]
          },
          {
            name: 'Batch status',
            type: 'select',
            key: 'status',
            className: 'pr20',
            defaultValue: '0',
            values: [
              { value: '0', name: 'Waiting' },
              { value: '1', name: 'Processing' },
              { value: '2', name: 'Succeeded' },
              { value: '-1', name: 'Failed' },
              { value: 'all', name: 'All' }
            ]
          },
          {
            name: 'Batch No',
            type: 'text',
            key: 'batchNo',
            className: 'pr20',
            placeHolder: 'Please enter the Batch No',
            values: []
          },
          {
            name: '',
            type: 'search',
            key: '',
            className: 'pr20',
            value: []
          }
        ],
        api: '/finance/query',
        loading: true,
      }
    }
  }

  componentDidMount () {
    this.getData()
  }

  getData () {
    this.setState({
      loading: true
    })

    let params = this.state.params
    const { transferDateStart, transferDateEnd, batchNo, status } = params

    let body = { transferDateStart, transferDateEnd, batchNo, status }

    fetchPost(`/servicecharge/pending/list?currentPage=${this.state.page.currentPage}&pageSize=${this.state.page.pageSize}`, body).then(json => {
      if (json.code === 0) {
        if (json.data != null) {
          this.setState({
            serviceChargeList: json.data.serviceChargeList,
            loading: false
          })
        }
      } else {
        this.setState({
          serviceChargeList: [],
          loading: false
        })
        message.error(json.msg)
      }
    })
  }

  nextpage (current) {
    this.setState({
      page: {
        ...this.state.page,
        currentPage: current,
        pageSize: PAGE_SIZE,
      }
    }, () => {
      this.getData()
    })
  }

  changeParams (params) {
    if (!params.status) {
      params.status = '0'
    }
    this.setState({
      params,
      page: {
        currentPage: 1,
        pageSize: PAGE_SIZE,
        totalCount: 0
      }
    }, () => {
      this.getData()
    })
  }

  renderRepaymentButton (record) {
    let text = 'operating'
    if (record.operationAllow) {
      return (<div>
        <Button type="primary" onClick={() => this.getServiceCharge(record.batchNo)}>{text}</Button>
      </div>)
    } else {
      return null
    }
  }

  renderDownloadButton (record) {
    let batchNo = record.batchNo
    let data = {
      batchNo
    }
    return <div>
      <DlButton downloadParams={data} buttonName='Export Detail' downloadUrl='/servicecharge/detail/list/export'/>
    </div>
  }

  getServiceCharge (batchNo) {
    fetchPost(`/servicecharge/info/get`, { batchNo }).then((res) => {
      if (res.code === 0) {
        this.setState({
          serviceChargeInfo: res.data.serviceChargeInfo,
          visible: true,
          currentBatchNo: batchNo
        })
      } else {
        message.error(res.msg)
      }
    })
  }

  handleOk () {
    let self = this
    if (this.state.serviceChargeInfo.operationAllow == 0) {
      message.error('The batch has been processed')
      this.setState({
        visible: !this.state.visible,
      }, () => {
        self.getData()
      })
    } else {
      this.props.form.validateFields((error) => {
        if (!error) {
          const { utrNo } = this.props.form.getFieldsValue()
          let batchNo = this.state.currentBatchNo
          fetchPost(`/servicecharge/transfer/submit`, { batchNo, utrNo }).then((res) => {
            if (res.code === 0) {
              self.props.form.resetFields()
              this.setState({
                visible: !this.state.visible
              }, () => {
                self.getData()
              })
            } else {
              message.error(res.msg)
            }
          })
        }
      })
    }
  }

  handleCancel () {
    this.setState({
      visible: !this.state.visible,
    })
    this.props.form.resetFields()
  }

  render () {
    const self = this
    const { getFieldDecorator } = this.props.form

    const columns = [
      {
        title: 'Transfer Date',
        dataIndex: 'transferDate',
        key: 'transferDate',
        width: '150',
      }, {
        title: 'Batch No',
        dataIndex: 'batchNo',
        key: 'batchNo',
        width: '200',
      }, {
        title: 'Total Amount',
        dataIndex: 'totalAmount',
        key: 'totalAmount',
        width: '120',
      }, {
        title: 'Order Count',
        dataIndex: 'orderCount',
        key: 'orderCount',
        width: '150',
      }, {
        title: 'Status',
        dataIndex: 'status',
        key: 'status',
        width: '120',
      }, {
        title: 'UTR',
        dataIndex: 'bankReferenceNo',
        key: 'bankReferenceNo',
        width: '150',
      }, {
        title: 'Detail',
        dataIndex: 'detail',
        key: 'detail',
        render: (text, record) => {
          return this.renderDownloadButton(record)
        }
      }, {
        title: 'operation',
        dataIndex: 'operation',
        key: 'operation',
        render: (text, record) => {
          return this.renderRepaymentButton(record)
        }
      }
    ]

    const pagination = {
      total: self.state.page.totalCount,
      pageSize: self.state.page.pageSize,
      showSizeChanger: false,
      showQuickJumper: true,
      showTotal (total) {
        return `Total ${total} `
      },
      onChange (current) {
        self.nextpage(current)
      }
    }

    return (
      <div>
        <Modal visible={this.state.visible} okText='Submit'
               onOk={() => {
                 this.handleOk()
               }} onCancel={() => {
          this.handleCancel()
        }}>
          <Form className={Styles.formWrapper}>
            <div className={Styles.info}>
              <div className={Styles.wrapper}>
                <Row gutter={8}>
                  <Col span={24} className='font14 mt10'>
                    Batch No:{this.state.serviceChargeInfo.batchNo}
                  </Col>
                </Row>
                <Row gutter={8}>
                  <Col span={12} className='font14 mt10'>
                    Transfer Date: {this.state.serviceChargeInfo.transferDate}</Col>
                  <Col span={12} className='font14 mt10'>
                    Product: {this.state.serviceChargeInfo.productCategoryCode}</Col>
                </Row>
                <Row gutter={8}>
                  <Col span={12} className='font14 mt10'>
                    Payment Channel: {this.state.serviceChargeInfo.paymentChannelCode}</Col>
                  <Col span={12} className='font14 mt10'>
                    Fund Account: {this.state.serviceChargeInfo.fundName}</Col>
                </Row>
                <Row gutter={8}>
                  <Col span={12} className='font14 mt10'>
                    Total Amount: {this.state.serviceChargeInfo.totalAmount}</Col>
                  <Col span={12} className='font14 mt10'>
                    Channel Fee: {this.state.serviceChargeInfo.channelFee}</Col>
                </Row>
                <Row gutter={8}>
                  <Col span={12} className='font14 mt10'>
                    Arrival Amount: {this.state.serviceChargeInfo.arrivalAmount}</Col>
                  <Col span={12} className='font14 mt10'>
                    Order Count: {this.state.serviceChargeInfo.orderCount}</Col>
                </Row>
                <Row gutter={8}>
                  <Col span={12} className='font14 mt10'>
                    UTR: {this.state.serviceChargeInfo.bankReferenceNo}</Col>
                  <Col span={12} className='font14 mt10'>
                    Status: {this.state.serviceChargeInfo.status}</Col>
                </Row>
              </div>

              <div>
                <Row gutter={8}>
                  <Col span={24} className='font14 mt10'>
                    <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} label='UTR:'>
                      {
                        getFieldDecorator('utrNo', {
                          rules: [{
                            required: true,
                            message: 'Please enter the UTR No.'
                          }]
                        })(
                          <Input type='text'/>
                        )
                      }
                    </FormItem>
                  </Col>
                </Row>
              </div>
            </div>
          </Form>
        </Modal>

        <div className={searchStyle.searchClass}>
          <Search searchParams={this.state.searchParams} changeParams={(params) => this.changeParams(params)}/>
        </div>

        <Table key='batchNo'
               style={{ marginTop: '20px' }}
               pagination={pagination}
               columns={columns}
               size='small'
               dataSource={this.state.serviceChargeList}
               loading={this.state.loading}
               bordered
        />

      </div>
    )
  }
}

ServiceCharge = Form.create()(ServiceCharge)
export default ServiceCharge
